import time
import pymysql
class DButils:
    def __init__(self,host,port,user,password,database,charset='utf8'):
        self.host=host
        self.port = port
        self.user=user
        self.password=password
        self.database=database
        self.charset=charset
        self.connection=None
        try:
            self.connection=(pymysql.connect
            (
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database,
                charset=self.charset
            ))
            print("数据库连接成功！")
        except pymysql.MySQLError as e:
            print(f"数据库连接失败:{e}")
    def execute(self,sql,params=None):
        """
        执行SQL语句（通用方法，适用于插入、更新、删除）
        :param sql:完整的SQL语句
        :param params:参数化查询的参数
        """
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql,params)
                self.connection.commit()
                print("操作成功！")
        except Exception as e:
            self.connection.rollback()
            print(f"操作失败！{e}")
        finally:
            cursor.close()
    def insert(self,sql,params=None):
        """
        查询数据
        :param sql:查询的SQL语句
        :param params:参数化查询的参数
        :return:查询结果
        """
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql,params)
                self.connection.commit()
                print("数据输入成功！")
        except Exception as e:
            self.connection.rollback()
            print(f"数据输入失败！{e}")
        finally:
            cursor.close()

    def update(self,sql,params=None):
        """更新数据"""
        db=self.connection
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,params)
                db.commit()
                print("数据更新成功！")
        except Exception as e:
            db.rollback()
            print(f"数据更新失败！{e}")
        finally:
            cursor.close()

    def select(self,sql,params=None):
        db=self.connection
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,params)
                result=cursor.fetchall()
                print("查询成功！")
                return result
        except Exception as e:
            db.rollback()
            print(f"查询失败！{e}")
        finally:
            cursor.close()
    def delete(self,sql,params=None):
        db=self.connection
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,params)
                db.commit()
                print("数据库删除成功！")
        except Exception as e:
            db.rollback()
            print(f"数据删除失败：{e}")
        finally:
            cursor.close()

    def close(self):
        if self.connection:
            self.connection.close()
            print("数据库连接已关闭")